<script setup lang="ts">
import { computed, onBeforeMount, ref, unref } from 'vue'
import { useBaseApi } from '@/api/base'
import { useRoute } from 'vue-router'
import { Close, CopyDocument } from '@element-plus/icons-vue'
import { copyTextToClipboard } from '@/utils'
import type { VxeToolbarProps } from 'vxe-table'
import type {
  BusinessUIAction,
  BusinessUIFormType,
  BusinessUIQueryType,
  BusinessUITableType,
  DicType,
  WorkflowDesignRow
} from '@/types/custom'
import mittBus from '@/utils/mitt'

import { ElMessage } from 'element-plus'
import { isNumber } from 'xe-utils'

import TemplateVxeGrid from '@/views/components/grid/components/TemplateVxeGrid.vue'

interface Props {
  disabled?: boolean
  params?: TypedAny
  insert?: boolean
  boxShadow?: boolean
  ready?: (value: number) => void
}

const route = useRoute()

const props = defineProps<Props>()

const emit = defineEmits(['fetch', 'close'])

const modelValue = defineModel<string>()

const { get_business_ui } = useBaseApi()

const modal = ref(false)
// 加载
const loading = ref(false)
// 查询栏
const uiQuery = ref<BusinessUIQueryType | undefined>()
// 表格
const uiTable = ref<BusinessUITableType | undefined>()
// 表单
const uiForm = ref<BusinessUIFormType | undefined>()
// 表单字典
const dicTable = ref<DicType[]>([])
// 查询字典
const dicQuery = ref<DicType[]>([])
// 按钮配置
const uiActions = ref<BusinessUIAction[]>([])
// 关联流程
const wfDesign = ref<WorkflowDesignRow | undefined>()
// 表格
const gridRef = ref()
// 工具栏配置
const toolbarConfig = ref<VxeToolbarProps>({})

const emptyText = computed(() => {
  return uiTable.value?.default_value_parse.emptyText || '暂无数据'
})

/**
 * 初始化mitt事件
 */
const onEventMitt = () => {
  if (uiTable.value && ['sys_workflow_list', 'sys_user_msg'].includes(uiTable.value.id)) {
    mittBus.on('onUpdateMsg', () => {
      onFetch()
    })
  }
}

/**
 * 格式化默认参数
 */
const onDefaultFetch = async () => {
  const id = unref(modelValue)
  if (!id) return
  loading.value = true
  return get_business_ui(id, true)
    .then(({ data }) => {
      const dic_table = data.dic_table || []
      const dic_query = data.dic_query || []
      const ui_table = data.ui_table
      const ui_query = data.ui_query
      const ui_form = data.ui_form
      const ui_actions = props.disabled ? [] : data.actions || []
      const wf_design = data.wf_design
      if (ui_table) {
        const { default_value_parse } = ui_table
        if (default_value_parse.toolbarConfig)
          toolbarConfig.value = default_value_parse.toolbarConfig
      }
      if (ui_table) uiTable.value = ui_table
      if (ui_query) uiQuery.value = ui_query
      if (ui_form) uiForm.value = ui_form

      dicQuery.value = dic_query
      dicTable.value = dic_table
      wfDesign.value = wf_design
      uiActions.value = ui_actions
      onEventMitt()
    })
    .finally(() => (loading.value = false))
}

const onFetch = () => {
  gridRef.value?.onFetch()
}

const copyText = ref<string[]>([])

/**
 * 按商品复制
 */
const handleCopyGrid = () => {
  const $grid = gridRef.value.getInstance()
  if ($grid) {
    const { fullData } = $grid.getTableData()
    if (fullData.length) {
      const list: string[] = []
      fullData.forEach((v: TypedAny, idx: number) => {
        list.push(`${idx + 1}.${v.product_name}（${v.model_name}）`)
        if (v.qty) {
          for (const k in v.qty) {
            list.push(`${v[`${k}_name`]} ${v[k]}`)
          }
        }
        list.push('')
      })
      copyText.value = list
      modal.value = true
    } else {
      ElMessage.warning('没有可复制数据')
    }
  }
}

/**
 * 按仓库复制
 */
const handleCityCopyGrid = () => {
  const $grid = gridRef.value.getInstance()
  if ($grid) {
    const { fullData } = $grid.getTableData()
    console.log(fullData)
    if (fullData.length) {
      const list: string[] = []
      // const item = fullData[0]
      const cityItems: SelectOptionType[] = []
      fullData.forEach((item: TypedAny) => {
        for (const k in item.qty) {
          if (item[`${k}_name`] && !cityItems.some((s) => s.value === k))
            cityItems.push({
              value: k,
              label: item[`${k}_name`]
            })
        }
      })

      cityItems.forEach((item, idx) => {
        list.push(`${idx + 1}、${item.label}`)
        const result = fullData.filter((f: TypedAny) => isNumber(f[item.value]))
        console.log(result)
        result.forEach((v: TypedAny) => {
          list.push(`${v.product_name} （${v.model_name}）`)
          list.push(`库存量：${v[item.value]}`)
        })
        list.push('')
      })
      copyText.value = list
      modal.value = true
    } else {
      ElMessage.warning('没有可复制数据')
    }
  }
}

const handleCopyText = () => {
  copyTextToClipboard(copyText.value.join('\n'))
  modal.value = false
}

onBeforeMount(() => {
  if (route.query.id) {
    modelValue.value = String(route.query.id)
  } else if (!modelValue.value) modelValue.value = String(route.meta.id)
  onDefaultFetch()
})

defineExpose({ onFetch, gridRef })
</script>

<template>
  <div>
    <TemplateVxeGrid
      ref="gridRef"
      v-model="loading"
      :params="params"
      :toolbar-config="toolbarConfig"
      :ui-form="uiForm"
      :ui-table="uiTable"
      :ui-query="uiQuery"
      :dic-query="dicQuery"
      :dic-table="dicTable"
      :ui-actions="uiActions"
      :wf-design="wfDesign"
      :box-shadow="boxShadow"
      :disabled="disabled"
      :insert="insert"
      :ready="ready"
      :empty-text="emptyText"
      @close="emit('close')"
      @fetch="emit('fetch')"
      :show-actions="['reload']"
    >
      <template #query_default>
        <el-button type="warning" :icon="CopyDocument" plain @click="handleCopyGrid">
          按商品复制
        </el-button>
        <el-button type="success" :icon="CopyDocument" plain @click="handleCityCopyGrid">
          按仓库复制
        </el-button>
      </template>
    </TemplateVxeGrid>
    <vxe-modal
      title="一键复制信息展示"
      v-model="modal"
      transfer
      resize
      destroy-on-close
      width="70%"
      height="70%"
    >
      <template #title>
        <el-space :size="5">
          <el-button :icon="Close" @click="modal = false">关闭</el-button>
          <el-button :icon="CopyDocument" type="primary" @click="handleCopyText">
            确认复制
          </el-button>
        </el-space>
      </template>
      <div style="white-space: pre-wrap" class="pa10 font14">
        {{ copyText.join('\n\r') }}
      </div>
    </vxe-modal>
  </div>
</template>
